package org.niceHome.controller;

import com.github.pagehelper.PageInfo;
import org.niceHome.base.BaseController;
import org.niceHome.entity.Admin;
import org.niceHome.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {

    private final static String PAGE_INDEX = "admin/index";
    private static final String PAGE_CREATE = "admin/create";
    private final static String PAGE_EDIT = "admin/edit";
    private final static String LIST_ACTION = "redirect:/admin";


    @Autowired
    private AdminService adminService;
    @RequestMapping
    public String index(@RequestParam Map<String,Object> filters, Model model){
        PageInfo<Admin> pageInfo = adminService.findPage(filters);
        model.addAttribute("page",pageInfo);
        model.addAttribute("filters",filters);
        return PAGE_INDEX;
    }

    @RequestMapping("/create")
    public String create(){
        return PAGE_CREATE;
    }

    @PostMapping("/save")
    public String save(Admin admin, Model model){
        adminService.insert(admin);
        return successPage(model,"新增用户成功");
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model){
        Admin admin = adminService.getById(id);
        model.addAttribute("admin",admin);
        return PAGE_EDIT;
    }

    @PostMapping("/update")
    public String update(Admin admin,Model model){
        adminService.update(admin);
        return successPage(model,"编辑用户成功");
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id){
        adminService.delete(id);
        return LIST_ACTION;
    }
}